package com.bjpowernode.crm.web.controller;

import com.bjpowernode.crm.constants.Constants;
import com.bjpowernode.crm.pojo.User;
import com.bjpowernode.crm.service.UserService;
import com.bjpowernode.crm.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("login.do")
    @ResponseBody
    public Map login(String username, String password, boolean autoLogin,
                     HttpServletRequest request, HttpServletResponse response) {
        // 不要使用localhost来访问
        String userIp = request.getRemoteAddr();

        User user = userService.getUser(username, password, userIp);

        request.getSession().setAttribute(Constants.LOGIN_USER, user);

        if (autoLogin) {
            int maxAge = 3600 * 24 * 10;
            Cookie cookie1 = new Cookie(Constants.CookieNames.USER_NAME, username);
            cookie1.setMaxAge(maxAge);
            cookie1.setPath("/");

            // 密码最好是加密存储
            Cookie cookie2 = new Cookie(Constants.CookieNames.USER_PWD, MD5Utils.getMD5(password));
            cookie2.setMaxAge(maxAge);
            cookie2.setPath("/");

            response.addCookie(cookie1);
            response.addCookie(cookie2);
        }

        return Constants.Result.SUC;
    }

    @GetMapping("logout.do")
    public String logout(HttpSession session, HttpServletResponse response) {
        session.removeAttribute(Constants.LOGIN_USER);

        // 同时清除cookie信息，防止免登陆
        Cookie cookie = new Cookie(Constants.CookieNames.USER_NAME, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);

        return "redirect:/";
    }

    @PostMapping("changePwd.do")
    @ResponseBody
    public Map changePwd(String oldPwd, String newPwd, HttpSession session) {
        User user = (User) session.getAttribute(Constants.LOGIN_USER);
        userService.changePwd(oldPwd, newPwd, user.getId());

        return Constants.Result.SUC_WITH_MSG;
    }

    @GetMapping("owners.json")
    @ResponseBody
    public List getOwners() {
        return userService.getOwners();
    }
}
